package com.terrace.web.tagext.easyui.utils;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.lang.StringUtils;

import com.terrace.core.mybatis.entity.Pagination;
import com.terrace.core.utils.JsonUtils;
import com.terrace.core.utils.reflect.ObjectPropertyHelper;
import com.terrace.web.constant.IconConstant;
import com.terrace.web.model.ComboTree;
import com.terrace.web.model.DataGrid;
import com.terrace.web.tagext.easyui.model.ComboTreeModel;
import com.terrace.web.tagext.easyui.model.TreeGridModel;

/**
 * easyui的Tree工具类
 * @author jiangyg
 *
 */
public class TreeUIUtils {
	
	/**
	 * 生成并输出Combo树的json
	 * @param cls				要转换ComboTree的Class
	 * @param model				ComboTree模型
	 * @param dataList			转换数据
	 * @param selectDataList	复选框选中的数据集合，可以传ID字段集合[List<String>]，也可以传实体类集合[List<cls>]
	 * @param response			请求响应
	 * @throws Exception
	 */
	public static void createComboTreeJson(ComboTreeModel model, List<?> dataList, List<?> selectDataList, HttpServletResponse response) throws Exception {
		ObjectPropertyHelper helper = new ObjectPropertyHelper(model.getCls());
		List<ComboTree> trees = iteratorTransferComboTree(helper, model, dataList);
		
		// 复选框选中状态
		if (selectDataList != null && selectDataList.size() > 0) {
			handleTreeSelectedState(helper, model, trees, selectDataList);
		}
		
		responseJsonPrint(response, JsonUtils.beanToJson(trees));
	}
	
	/**
	 * 生成并输出TreeGrid表格树的JSON
	 * @param model
	 * @param pagination
	 * @param response
	 * @throws Exception
	 */
	public static void createTreeGridJson(TreeGridModel model, Pagination<?> pagination, HttpServletResponse response) throws Exception {
		ObjectPropertyHelper helper = new ObjectPropertyHelper(model.getCls(), true);
		// 结果集
		List<?> results = pagination.getResult();
		// 转换之后的结果集
		List<Map<String, Object>> rows = iteratorTransferTreeGrid(helper, model, results);
		
		// 结果输出
		if (pagination.isPagination()) {
			DataGrid<Map<String, Object>> dataGrid = new DataGrid<Map<String, Object>>();
			dataGrid.setTotal(pagination.getTotal());
			dataGrid.setRows(rows);
			responseJsonPrint(response, JsonUtils.beanToJson(dataGrid));
		} else {
			responseJsonPrint(response, JsonUtils.beanToJson(rows));
		}
		
	}
	
	/**
	 * 输出JSON
	 * @param response
	 * @param result
	 * @throws IOException
	 */
	public static void responseJsonPrint(HttpServletResponse response, String result) throws IOException {
		response.setCharacterEncoding("UTF-8");
		response.setContentType("application/json");
		response.setHeader("Cache-Control", "no-store");
		// json输出
		PrintWriter out = response.getWriter();
		out.print(result);
	}
	
	/**
	 * 处理树以选中的状态
	 * @param helper
	 * @param model
	 * @param dataList
	 * @param selectDataList
	 * @throws Exception 
	 */
	private static void handleTreeSelectedState(ObjectPropertyHelper helper, ComboTreeModel model, List<ComboTree> trees, List<?> selectDataList) throws Exception {
		for (Object selectObj : selectDataList) {
			
			if (selectObj instanceof String) {
				
				// 表示选中信息是id列表
				String idValue = ObjectUtils.toString(selectObj);
				for (ComboTree comboTree : trees) {
					// 元素有子集
					List<ComboTree> childrenComboTree = comboTree.getChildren();
					if (childrenComboTree != null && childrenComboTree.size() > 0) {
						handleTreeSelectedState(helper, model, childrenComboTree, selectDataList);
					} else if (comboTree.getId().equals(idValue)) {
						comboTree.setChecked(true);
					}
				}
				
			} else {
				
				// 表示选中信息是实体对象
				String idValue = helper.invokeGetMothod(model.getIdField(), selectObj);
				for (ComboTree comboTree : trees) {
					if (comboTree.getId().equals(idValue)) {
						// 元素有子集
						List<ComboTree> childrenComboTree = comboTree.getChildren();
						if (childrenComboTree != null && childrenComboTree.size() > 0) {
							// 获取对应元素选中的子集列表
							List<Object> selectChildList = helper.invokeGetMothod(model.getChildrenField(), selectObj);
							if (selectChildList != null && selectChildList.size() > 0) {
								handleTreeSelectedState(helper, model, childrenComboTree, selectChildList);
							}
						} else {
							comboTree.setChecked(true);
						}
						break;
					}
				}
				
			}
			
		}
	}
	
	private static List<Map<String, Object>> iteratorTransferTreeGrid(ObjectPropertyHelper helper, TreeGridModel model, List<?> results) throws Exception {
		// 转换之后的结果集
		List<Map<String, Object>> rows = new ArrayList<Map<String, Object>>(results.size() + 1);
		
		List<String> propertyNames = helper.getFieldNames();

		for (Object object : results) {
			Map<String, Object> result = new HashMap<String, Object>();
			
			// 遍历属性值
			for (String propertyName : propertyNames) {
				result.put(propertyName, helper.invokeGetMothod(propertyName, object));
			}
			
			// 子集处理
			if (StringUtils.isNotBlank(model.getChildrenField())) {
				List<?> childList = helper.invokeGetMothod(model.getChildrenField(), object);
				List<Map<String, Object>> childResults = null;
				if (childList != null && childList.size() > 0) {
					childResults = iteratorTransferTreeGrid(helper, model, childList);
					result.put("state", model.isState() ? "open" : "closed");
				}
				result.put("children", childResults);
			}
			
			rows.add(result);
		}
		
		return rows;
	}
	
	/**
	 * 把结果集迭代转化成树列表结合
	 * @param helper
	 * @param model
	 * @param dataList
	 * @return
	 * @throws Exception 
	 */
	private static List<ComboTree> iteratorTransferComboTree(ObjectPropertyHelper helper, ComboTreeModel model, List<?> dataList) throws Exception {
		List<ComboTree> trees = new ArrayList<ComboTree>();
		
		for (Object obj : dataList) {
			
			ComboTree tree = new ComboTree();
			
			String idValue = helper.invokeGetMothod(model.getIdField(), obj);
			tree.setId(idValue);
			
			String textValue = helper.invokeGetMothod(model.getTextField(), obj);
			tree.setText(textValue);
			
			if (StringUtils.isNotBlank(model.getIconClsField())) {
				String iconValue = helper.invokeGetMothod(model.getIconClsField(), obj);
				tree.setIconCls(IconConstant.obtainIconClass(iconValue));
			}
			
			if (StringUtils.isNotBlank(model.getChildrenField())) {
				List<?> childrenData = helper.invokeGetMothod(model.getChildrenField(), obj);
				if (childrenData != null) {
					tree.setChildren(iteratorTransferComboTree(helper, model, childrenData));
				}
			}
			
			trees.add(tree);
		}
		
		return trees;
	}
	
	/**
	public static void main(String[] args) throws Exception {
		List<Permission> list = new ArrayList<Permission>();
		for (int i = 0; i < 10; i++) {
			Permission p = new Permission();
			p.setId("id_" + i);
			p.setPermiName("permiName_" + i);
			
			List<Permission> child = new ArrayList<Permission>();
			for (int j = 0; j < 10; j++) {
				Permission p1 = new Permission();
				p1.setId("child_id_" + i);
				p1.setPermiName("child_permiName_" + i);
				child.add(p1);
			}
			p.setChildrenPermis(child);
			
			list.add(p);
		}
		
		ObjectPropertyHelper helper = new ObjectPropertyHelper(Permission.class, true);
		TreeGridModel model = new TreeGridModel(Permission.class, "childrenPermis");
		
		System.out.println(JsonUtils.beanToJson(iteratorTransferTreeGrid(helper, model, list)));
		
	}
	**/

}
